package cn.stylefeng.guns.modular.storage.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicWarehouseResult;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.storage.entity.StorageOutDetailed;
import cn.stylefeng.guns.modular.storage.entity.StorageStock;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutDetailedParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutParam;
import cn.stylefeng.guns.modular.storage.model.params.StoragePutSingleParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutDetailedResult;
import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import cn.stylefeng.guns.modular.storage.service.StorageOutDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.sys.core.util.CacheUtil;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 拣货单明细表控制器
 */
@Controller
@RequestMapping("/storageOutDetailed")
public class StorageOutDetailedController extends BaseController {

    private String PREFIX = "/storage/storageOutDetailed";

    @Autowired
    private StorageOutDetailedService storageOutDetailedService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicGoodsService basicGoodsService;

    @Autowired
    private BasicPositionService basicPositionService;

    @Autowired
    private StorageStockService storageStockService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    /**
     * 跳转 0出库页面
     */
    @RequestMapping("toOut0")
    public String toOut0() {
        return PREFIX + "/out0.html";
    }

    /**
     * 跳转 拣选作业汇总统计
     */
    @RequestMapping("jianxuanzuoyehuizong")
    public String jianxuanzuoyehuizong(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/jianxuanzuoyehuizong.html";
    }

    /**
     * 查询 拣选作业汇总
     */
    @ResponseBody
    @RequestMapping("/findjianxuanzuoyehuizong")
    public LayuiPageInfo findjianxuanzuoyehuizong(StorageOutDetailedParam storageOutDetailedParam, String condition, Long outStorehouseId , String startSingleTime, String endSinglePutTime) {
    	if (ToolUtil.isNotEmpty(startSingleTime) && ToolUtil.isNotEmpty(endSinglePutTime)) {
    		storageOutDetailedParam.setNotes("'"+startSingleTime+"' and '"+endSinglePutTime+"'");
		}
    	if (startSingleTime == null && endSinglePutTime == null) {
    		storageOutDetailedParam.setNotes("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
		}
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	if(outStorehouseId == null) {
    		List<BasicWarehouseResult> wlist = basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId());
    		if(wlist.size() > 0) {
    			outStorehouseId = Long.parseLong(wlist.get(0).getId().toString());
    		}
    	}
    	List<StorageOutDetailedResult> list = storageOutDetailedService.findjianxuanzuoyehuizong(storageOutDetailedParam,condition,outStorehouseId,deptId,deliverId,user.getOperateId());
    	LayuiPageInfo LayuiPageInfo = new LayuiPageInfo();
    	LayuiPageInfo.setData(list);
    	LayuiPageInfo.setCount(list.size());
    	return LayuiPageInfo;
    }

    /**
     * 查询 拣选作业日汇总
     */
    @ResponseBody
    @RequestMapping("/findjianxuanzuoyehuizongRi")
    public LayuiPageInfo findjianxuanzuoyehuizongRi(StorageOutDetailedParam storageOutDetailedParam, String condition, Long outStorehouseId , String startSingleTime, String endSinglePutTime) {
    	if (ToolUtil.isNotEmpty(startSingleTime) && ToolUtil.isNotEmpty(endSinglePutTime)) {
    		storageOutDetailedParam.setNotes("'"+startSingleTime+"' and '"+endSinglePutTime+"'");
		}
    	if (startSingleTime == null && endSinglePutTime == null) {
    		storageOutDetailedParam.setNotes("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
		}
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	if(outStorehouseId == null) {
    		List<BasicWarehouseResult> wlist = basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId());
    		if(wlist.size() > 0) {
    			outStorehouseId = Long.parseLong(wlist.get(0).getId().toString());
    		}
    	}
    	List<StorageOutDetailedResult> list = storageOutDetailedService.findjianxuanzuoyehuizongRi(storageOutDetailedParam,condition,outStorehouseId,deptId,deliverId,user.getOperateId());
    	LayuiPageInfo LayuiPageInfo = new LayuiPageInfo();
    	LayuiPageInfo.setData(list);
    	LayuiPageInfo.setCount(list.size());
    	return LayuiPageInfo;
    }

    /**
     * 跳转 货品出库量汇总统计
     */
    @RequestMapping("huopinchukulianghuizong")
    public String huopinchukulianghuizong(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/huopinchukulianghuizong.html";
    }

    /**
     * 查询 货品出库量汇总
     */
    @ResponseBody
    @RequestMapping("/findhuopinchukulianghuizong")
    public LayuiPageInfo findhuopinchukulianghuizong(StorageOutDetailedParam storageOutDetailedParam, String condition, Long outStorehouseId , String startSingleTime, String endSinglePutTime) {
    	if (ToolUtil.isNotEmpty(startSingleTime) && ToolUtil.isNotEmpty(endSinglePutTime)) {
    		storageOutDetailedParam.setNotes("'"+startSingleTime+"' and '"+endSinglePutTime+"'");
		}
    	if (startSingleTime == null && endSinglePutTime == null) {
    		storageOutDetailedParam.setNotes("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
		}
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	if(outStorehouseId == null) {
    		List<BasicWarehouseResult> wlist = basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId());
    		if(wlist.size() > 0) {
    			outStorehouseId = Long.parseLong(wlist.get(0).getId().toString());
    		}
    	}
    	List<StorageOutDetailedResult> list = storageOutDetailedService.findhuopinchukulianghuizong(storageOutDetailedParam,condition,outStorehouseId,deptId,deliverId,user.getOperateId());
    	LayuiPageInfo LayuiPageInfo = new LayuiPageInfo();
    	LayuiPageInfo.setData(list);
    	LayuiPageInfo.setCount(list.size());
    	return LayuiPageInfo;
    }

    /**
     * 跳转到出库记录
     */
    @RequestMapping("outjilu")
    public String outjilu(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
//    	model.addAttribute("startSingleTime",DateUtil.getPastDate(7));
//    	model.addAttribute("endSinglePutTime",DateUtil.getDate());
        return PREFIX + "/outjilu.html";
    }

    /**
     * 查询出库记录
     */
    @ResponseBody
    @RequestMapping("/chukujilu")
    public LayuiPageInfo chukujilu(StorageOutDetailedParam storageOutDetailedParam, String condition, Long outStorehouseId , String startSingleTime, String endSinglePutTime, String startTime, String endTime) {
    	if (ToolUtil.isNotEmpty(startSingleTime) && ToolUtil.isNotEmpty(endSinglePutTime)) {
    		storageOutDetailedParam.setNotes("'"+startSingleTime+"' and '"+endSinglePutTime+"'");
		}
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		storageOutDetailedParam.setStoragePutcondition("'"+startTime+"' and '"+endTime+"'");
		}
//    	if (startSingleTime == null && endSinglePutTime == null) {
//    		storageOutDetailedParam.setNotes("'"+DateUtil.getPastDate(7)+"' and '"+DateUtil.getDate()+"'");
//		}
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	return this.storageOutDetailedService.findPageBySpecChukujilu(storageOutDetailedParam,condition,outStorehouseId,deptId,deliverId,user.getOperateId());
    }

    /**
     * 导出Excel
     */
    @RequestMapping("/exportExcelBySpec")
    public void exportExcelBySpec(HttpServletResponse response, StorageOutDetailedParam storageOutDetailedParam, String condition2, Long outStorehouseId , String startSingleTime, String endSinglePutTime, String startTime, String endTime) throws IOException {
    	if (ToolUtil.isNotEmpty(startSingleTime) && ToolUtil.isNotEmpty(endSinglePutTime)) {
    		storageOutDetailedParam.setNotes("'"+startSingleTime+"' and '"+endSinglePutTime+"'");
		}
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		storageOutDetailedParam.setStoragePutcondition("'"+startTime+"' and '"+endTime+"'");
		}
    	storageOutDetailedParam.setOutStorehouseId(outStorehouseId);
    	storageOutDetailedParam.setCondition2(condition2);
        Workbook wb = storageOutDetailedService.exportToExcel(storageOutDetailedParam);
        OutputStream output = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Outbound Record Information" + ".xlsx").getBytes(), "iso-8859-1"));
        wb.write(output);
        output.close();
    }

    /**
     * 跳转到主页面
     *
     * @author hu
     * @Date 2019-07-15
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/storageOutDetailed.html";
    }

    /**
     * 批量打印拣货单  页面
     */
    @RequestMapping("print")
    public String print(StorageOutParam storageOutParam,Long[] ids,Model model) {
    	CacheUtil.put("storageOutprintIds", "ids", ids);
		String getUnit = storageOutParam.getGetUnit();
		String getLocation = storageOutParam.getGetLocation();
		//解决参数中的 英文括号
    	if (getUnit!=null&&getUnit!="") {
    		getUnit = getUnit.replace("& #40;", "(");
    		getUnit = getUnit.replace("& #41;", ")");
    		storageOutParam.setGetUnit(getUnit);
		}
    	if (getLocation!=null&&getLocation!="") {
    		getLocation = getLocation.replace("& #40;", "(");
    		getLocation = getLocation.replace("& #41;", ")");
    		storageOutParam.setGetLocation(getLocation);
		}
    	model.addAttribute("storageOutParam", storageOutParam);
        return PREFIX + "/print.html";
    }

    /**
     * 拣货单查询商品明细
     * @author zhucx
     * @Date 2019-09-06
     */
    @RequestMapping("toQuery")
    public String toQuery(StorageOutDetailedParam storageOutDetailedParam,Model model) {
    	model.addAttribute("storageOutDetailedParam", storageOutDetailedParam);
    	return PREFIX + "/queryDetailed.html";
    }

    /**
     * 去合单详情页面
     * @author hu
     * @Date 2019-07-08
     */
    @RequestMapping("/toMrakDetailed")
    public String toMrakDetailed(StorageOutParam storage,Model model) {
        model.addAttribute("storage", storage);
        return PREFIX + "/storageDetailed.html";
    }

    /**
     * 查询商品列表
     * @author zhucx
     * @Date 2019-07-08
     */
    @ResponseBody
    @RequestMapping("/listGoods")
    public LayuiPageInfo listGoods(StorageOutDetailedParam storageOutDetailedParam) {
        storageOutDetailedParam.setStorageOutStatus("NOT_STARTED");
        return this.storageOutDetailedService.findDistinctGoods(storageOutDetailedParam);
    }
    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(@RequestParam("storageOutNumber")String storageOutNumber, @RequestParam("goodsId")Long goodsId, Model model) {
        BasicGoods basicGoods = basicGoodsService.getById(goodsId);
        model.addAttribute("storageOutNumber", storageOutNumber);
        model.addAttribute("basicGoods", basicGoods);
        return PREFIX + "/storageOutDetailed_add.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/storageOutDetailed_edit.html";
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(StorageOutDetailedParam storageOutDetailedParam) {
        this.storageOutDetailedService.add(storageOutDetailedParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(StorageOutDetailedParam storageOutDetailedParam) {
        StorageOutDetailed storage = storageOutDetailedService.getById(storageOutDetailedParam.getId());
        //库位编号
        storage.setStoragePostionNumber(storageOutDetailedParam.getStoragePostionNumber());
        //应入大包数
        storage.setStoragePutbalenum(storageOutDetailedParam.getStoragePutbalenum());
        //应入数量
        storage.setStorageNumber(storageOutDetailedParam.getStorageNumber());
        //批号
        storage.setStorageBatchnumber(storageOutDetailedParam.getStorageBatchnumber());
        //入库数量
        int storageNumber = Integer.parseInt(storageOutDetailedParam.getStorageNumber());
        //重量
        Integer weight = Integer.parseInt(storage.getStorageWeight());
        //体积
        Integer volume = Integer.parseInt(storage.getStorageVolume());
        //单价
        Double price = Double.parseDouble(storage.getStorageMoney());
        //应入重量
        storage.setStorageWeight(String.valueOf(weight * storageNumber));
        //应入体积
        storage.setStorageVolume(String.valueOf(volume * storageNumber));
        //应入金额
        storage.setStorageMoney(String.valueOf(price * storageNumber));
        StorageOutDetailedParam outDetailedParam = new StorageOutDetailedParam();
        ToolUtil.copyProperties(storage,outDetailedParam);
        this.storageOutDetailedService.update(storageOutDetailedParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(StorageOutDetailedParam storageOutDetailedParam) {
        this.storageOutDetailedService.delete(storageOutDetailedParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(StorageOutDetailedParam storageOutDetailedParam) {
        StorageOutDetailed detail = this.storageOutDetailedService.getById(storageOutDetailedParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 批量分配库位
     */
    @RequestMapping("/pointsPosition")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class)
    public ResponseData pointsPosition(Long[] ids,String positionNumber) {
    	for (Long id :ids) {
    		StorageOutDetailed storageOutDetailed = this.storageOutDetailedService.getById(id);
    		storageOutDetailed.setStoragePostionNumber(positionNumber);
    		StorageOutDetailedParam param = new StorageOutDetailedParam();
            ToolUtil.copyProperties(storageOutDetailed,param);
            storageOutDetailedService.update(param);
		}
        return ResponseData.success();
    }

    /**
     * 查询库位列表
     */
    @ResponseBody
    @RequestMapping("/positionList")
    public LayuiPageInfo positionList(BasicPositionParam basicPositionParam, String condition, String StorageOutNumber ) {
    	User user = userService.getcurrentUser();
        basicPositionParam.setDeliverId(user.getDeliverId());
        Long deptId = user.getDeptId();
        StorageOutParam storageOutParam = new StorageOutParam();
        storageOutParam.setStorageOutNumber(StorageOutNumber);
        LayuiPageInfo layuipageinfo = this.basicPositionService.findPageBySpec(basicPositionParam,condition,deptId,storageOutParam.getOutStorehouseId(),user.getOperateId());
        return layuipageinfo;
    }

    /**
     * 选择库位页面
     */
    @RequestMapping("/toChosePosition")
    public String toChosePosition(@RequestParam("storageOutNumber")String storageOutNumber,Model model) {
        model.addAttribute("storageOutNumber", storageOutNumber);
        return PREFIX + "/ChosePosition.html";
    }

    /**
     * 查询合单商品明细或者未合单商品明细详情
     * @param storage
     * @param condition
     * @return
     */
    @ResponseBody
    @RequestMapping("/getmarklist")
    public LayuiPageInfo getmarklist(StorageOutParam storage, String condition) {
        return this.storageOutDetailedService.findByMark(storage,condition);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/querylist")
    public LayuiPageInfo querylist(StorageOutDetailedParam storageOutDetailedParam,String condition ) {
        return this.storageOutDetailedService.findPageBySpec(storageOutDetailedParam,condition);
    }

    /**
     * 拣货单打印
     * 查询拣货单明细
     */
    @ResponseBody
    @RequestMapping("/getPrintstorageOutDetailed")
    public List<StorageOutDetailedResult> getPrintstorageOutDetailed(StorageOutDetailedParam storageOutDetailedParam) {
        return this.storageOutDetailedService.getPrintstorageOutDetailed(storageOutDetailedParam);
    }

    /**
     * 修改库位
     */
    @ResponseBody
    @RequestMapping("/change")
    @Transactional(rollbackFor = Exception.class)
    public ResponseData change(StorageOutDetailedParam storageOutDetailedParam,String postionNumber
    		,String outnum ) {
    	StorageOutDetailed storageOutDetailed = storageOutDetailedService.getById(storageOutDetailedParam.getId());
    	ResponseData data = new ResponseData();
    	if (postionNumber.equals(storageOutDetailed.getStoragePostionNumber())) {
    		data.setMessage("Same location");
    		data.setSuccess(false);
    		return data;
		}
    	StorageStockParam param = new StorageStockParam();
    	param.setStockstate("IN_STOCK");
    	param.setTrayNumber(storageOutDetailed.getTrayNumber());
    	StorageStockResult storageStockResult = storageStockService.findBySpec(param);

    	StorageStock stock = storageStockService.getById(storageOutDetailed.getStockId());
    	BigDecimal tnum = new BigDecimal(stock.getNum());
		StorageStockParam param2 = new StorageStockParam();
    	if (storageStockResult!=null) {
			BigDecimal snum = new BigDecimal(storageStockResult.getNum());
			snum = snum.add(tnum);
			storageStockResult.setNum(snum.toString());
	        ToolUtil.copyProperties(storageStockResult, param2);
	        storageStockService.update(param2);//修改拆托 原托数量
		}

        ToolUtil.copyProperties(stock, param2);
        storageStockService.delete(param2);//删除待拣托

        StorageStockParam param3 = new StorageStockParam();
        param3.setNum(outnum);
        param3.setStockstate("IN_STOCK");
        param3.setPositionNumber(postionNumber);
        param3.setGoodsId(storageOutDetailed.getStorageGoodsId());
        StorageStockResult sr2 =  storageStockService.findBySpec(param2);
        if (sr2==null) {
			data.setMessage("Insufficient inventory in location");
			data.setSuccess(false);
			return data;
		} else {
			BigDecimal nnum = new BigDecimal(sr2.getNum());
			BigDecimal outnum2 = new BigDecimal(outnum);
			if (nnum.compareTo(outnum2)==0) {
				sr2.setStockstate("PENDING_SHIPMENT");
		        ToolUtil.copyProperties(sr2, param2);
		        storageStockService.update(param2);//修改新托盘 库存状态

		        storageOutDetailed.setStockId(Long.parseLong(param2.getId().toString()));
		        storageOutDetailed.setTrayNumber(sr2.getTrayNumber());
		        storageOutDetailed.setStoragePostionNumber(sr2.getPositionNumber());
		        storageOutDetailed.setStorageNumber(outnum);
		        storageOutDetailed.setStoragePutbalenum(outnum);
		        storageOutDetailed.setStorageBatchnumber(sr2.getGoodsbatchs());
		        ToolUtil.copyProperties(storageOutDetailed, storageOutDetailedParam);
		        storageOutDetailedService.update(storageOutDetailedParam);//修改拣货单明细
			} else {
				BigDecimal ys = nnum.subtract(outnum2);
				StorageStockParam param4 = new StorageStockParam();
            	String uuid = UUID.randomUUID().toString().replaceAll("-","");
		        ToolUtil.copyProperties(sr2, param4);
		        param4.setNum(outnum);
		        param4.setStockstate("PENDING_SHIPMENT");
		        param4.setMark(uuid);
		        storageStockService.add(param4);

		        sr2.setNum(ys.toString());
		        ToolUtil.copyProperties(sr2, param4);
		        storageStockService.update(param4);//修改新托盘 库存状态

				StorageStockParam param5 = new StorageStockParam();
				param5.setMark(uuid);
				StorageStockResult result = storageStockService.findBySpec(param5);
				storageOutDetailed.setStockId(Long.parseLong(result.getId().toString()));
				storageOutDetailed.setTrayNumber(result.getTrayNumber());
				storageOutDetailed.setStoragePostionNumber(result.getPositionNumber());
				storageOutDetailed.setStorageNumber(outnum);
		        storageOutDetailed.setStoragePutbalenum(outnum);
		        storageOutDetailed.setStorageBatchnumber(result.getGoodsbatchs());
		        storageOutDetailedService.update(storageOutDetailedParam);//修改拣货单明细
			}

		}
        return ResponseData.success();
    }
}


